package controller;
import modle.DAO.UserDao;
import modle.Bean.JDBCUtil;
import modle.Bean.User;

import java.io.IOException;
import java.io.Serial;
import java.sql.Connection;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/ModifyPassword")
public class ModifyPasswordServlet extends HttpServlet {
    @Serial
    private static final long serialVersionUID = 2L;
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取当前登录用户信息
        User user = (User)request.getSession().getAttribute("user");
        String oldPassword = request.getParameter("old_password");
        String newPassword = request.getParameter("new_password");

        JDBCUtil db = new JDBCUtil();
        Connection conn = db.getConn();
        // 调用DAO层验证用户密码
        UserDao userDao = new UserDao();
        try {
            if(userDao.verifyUser(conn,user,oldPassword)) {
                // 密码验证通过，更新数据库中用户密码
                userDao.updatePassword(conn,user, newPassword);
                request.setAttribute("errorMsg", "请重新登录！");
                RequestDispatcher rd = request.getRequestDispatcher( "/index.jsp");
                rd.forward(request, response);
            }
        } catch (Exception e) {

            throw new RuntimeException(e);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

}
